package com.hxm.demo.newcoder;

public class TestBM3 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = reverseKGroup2(head, 2);
        System.out.println(listNode);
    }

    public static ListNode reverseKGroup1(ListNode head, int k) {
        // write code here
        if (head == null || head.next == null || k == 1) {
            return head;
        }
        ListNode pre = new ListNode(-1);
        ListNode result = pre;
        while (head != null) {
            ListNode newListNode = null;
            int i = 0;
            while (head != null && i < k) {
                ListNode temp = head.next;
                head.next = newListNode;
                newListNode = head;
                head = temp;
                if (pre.next != null) {
                    pre = pre.next;
                }
                i++;
            }
            if (i == k) {
                pre.next = newListNode;
            } else {
                while (pre.next != null) {
                    pre = pre.next;
                }
                ListNode tail = null;
                for (int j = 0; j < i; j++) {
                    ListNode temp = newListNode.next;
                    newListNode.next = tail;
                    tail = newListNode;
                    newListNode = temp;
                }
                pre.next = tail;
            }
        }
        return result.next;
    }

    public static ListNode reverseKGroup2(ListNode head, int k) {
        // write code here
        ListNode tail = head;
        for (int i = 0; i < k; i++) {
            if (tail == null) {
                return head;
            }
            tail = tail.next;
        }

        ListNode pre = null;
        ListNode cur = head;

        while (cur != tail) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        head.next = reverseKGroup2(tail, k);
        return pre;
    }
}
